#!/bin/sh

#Note this is replaced by make install, not configure!
export MX_MODULE_DIR=@mx_module_dir@


# Override the MacOS boot-time shell's builtin echo which
# errors out if stdout does not exist.

echo ()
{
  /bin/echo "$@"
}

set -e

if test ! -d ${MX_MODULE_DIR}; then
    echo "Something bad happened with the install script"
    echo "MX_DIR isn't pointing to a valid directory"
    exit 1
fi


# Remove the MX modules if loaded
unload_mx() {
    ${MX_MODULE_DIR}/mx_stop_mapper

    if /usr/sbin/kextstat | grep 'mx_ethernet' > /dev/null; then
	echo "Removing mx ethernet"
	/sbin/kextunload -m com.Myricom.iokit.mx_ethernet
    fi
	
    if /usr/sbin/kextstat | grep 'mx_driver' > /dev/null; then
	echo "Removing mx driver"
	/sbin/kextunload -m com.Myricom.iokit.mx_driver
    fi
	
    if /usr/sbin/kextstat | grep 'mx_mcp' > /dev/null; then
	echo "Removing mx mcp"
	/sbin/kextunload -m com.Myricom.kext.mx_mcp
    fi
}

# Remove the GM module if loaded
unload_gm() {
    if sysctl net.gm 2>&1 | grep -q gm; then
	echo "Removing gm driver"
	
	unit=`sysctl net.gm.gm_base_en_unit | awk '{print $2}'`
	maxunit=`echo $unit | awk '{print 4 + $1}'`
        while [ $unit -le $maxunit ]
        do
            device="en$unit"
# ifconfig does not delete ipv6 addresses, even though
# it adds one automatically when an ipv4 address is added.
            if [ -x /usr/sbin/ip6 ]
            then
                /usr/sbin/ip6 -d $device >/dev/null 2>&1
            fi
            ifconfig $device down delete >/dev/null 2>&1
            unit=`echo $unit | awk '{print 1 + $1}'`
        done
	
	/sbin/kextunload -m com.Myricom.iokit.gm
    fi
}

# Load the MX modules
load_mx() {
    echo "Loading mx driver"
    cd ${MX_MODULE_DIR}/load
    kextload -s . -t  mx_mcp.kext
    kextload -s . -r . mx_driver.kext mx_ethernet.kext
    ${MX_MODULE_DIR}/mx_start_mapper
}


case "$1" in
    start|"")
	unload_gm
	load_mx
	;;
    stop)
	unload_mx
	;;
    start-mapper)
	${MX_MODULE_DIR}/mx_start_mapper
	;;
    stop-mapper)
	${MX_MODULE_DIR}/mx_stop_mapper
	;;
    status)
	if /usr/sbin/kextstat | grep 'mx_driver' > /dev/null; then
	    echo "MX driver is loaded"
	else
	    echo "MX driver is not loaded"
	fi
	;;
    restart)
	unload_gm
	unload_mx
	load_mx
	;;
    *)
	echo $"Usage: $0 {start|stop|start-mapper|stop-mapper|status|restart}"
        exit 1
esac

exit 0
